// pages/cart/cart.js
//使用async await需要引入，只引入就行
import regeneratorRuntime from '../../lib/runtime/runtime'
import { 
  z_getSetting, z_chooseAddress, z_openSetting
 } from '../../utils/async_wx'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address:{},
    goodsInfo:[],
    priceCount:{}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAddress()
  },

  //去到详情页面
  goDetailPages(event){
    const {id} = event.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/goods_detail/goods_detail?id=' + id,
    });
  },

  //结算
  settleAccount() {
    const {address, goodsInfo} = this.data
    // console.log('结算')
    // 1.判断是否有选中商品
    const checkGoods = goodsInfo.filter(item => item.select)
    if(checkGoods.length === 0){
      wx.showToast({
        title: '尚未选择商品~',
        icon:'none',
        duration: 1000,
        mask: true,      
      });
      return
    }
    if(!address.userName){
      wx.showToast({
        title: '请先填写收货地址~',
        icon:'none',
        duration: 1000,
        mask: true,      
      });
      return
    }
    wx.navigateTo({
      url: '/pages/pay/pay'
    });
    
  },

  //获取当前商品价格和数量
  getTotalPriceCount(){
    let obj = {price:0, count:0}
    const {goodsInfo} = this.data
    goodsInfo.forEach(item => {
    if(item.select === true){
      obj.price += parseInt(item.goods_price) * parseInt(item.count)
      obj.count += parseInt(item.count)
    }
    })
    this.setData({priceCount:obj})
  },

  //全选
  allSelect(detail) {
    const {all} = detail.detail
    let {goodsInfo} = this.data;
    if(all){
      goodsInfo.forEach(item => {
        item.select = true
      })
    }else{
      goodsInfo.forEach(item => {
        item.select = false
      })
    }
    this.setData({goodsInfo:[...this.data.goodsInfo]})
    wx.setStorageSync('cart',goodsInfo)
    this.getTotalPriceCount()
  },

  //是否选中当前商品
  isSelect(event) {
    const goods_id = event.currentTarget.dataset.id
    //获取购物车数组
    let {goodsInfo} = this.data;
    // 找到被修改的商品对象
    let index = goodsInfo.findIndex(item=>item.goods_id === goods_id);
    //找到后 取反
    goodsInfo[index].select =! goodsInfo[index].select
    //将 数组重新填回data中 和缓存中
    wx.setStorageSync('cart',goodsInfo );
    this.setData({
      goodsInfo
    })
    // console.log(!undefined)
    // console.log()
    this.selectComponent('#cart_bar').isSelect()
    this.getTotalPriceCount()
  },

  //减少货物数量
  decreaseGoodCount(event) {
    const goods_id = event.currentTarget.dataset.id
    const result = wx.getStorageSync('cart') || []
    let good_index = result.findIndex(item =>
        item.goods_id === goods_id)
    result[good_index].count--
    if(result[good_index].count===0){
      result.splice(good_index,1)
    }
    this.setData({goodsInfo:result})
    wx.setStorageSync('cart', result);
    this.getTotalPriceCount()
  },
  //增加货物数量
  increaseGoodCount(event) {
    const goods_id = event.currentTarget.dataset.id
    const result = wx.getStorageSync('cart') || []
    let good_index = result.findIndex(item =>
        item.goods_id === goods_id)
    result[good_index].count++
    this.setData({goodsInfo:result})
    wx.setStorageSync('cart', result);
    this.getTotalPriceCount()
  },

  //获取本地存储的商品信息
  getGoodsInfo() {
    const goodsInfo = wx.getStorageSync('cart') || [];
    this.setData({
      goodsInfo
    })
  },

  //点击按钮获取收获地址
  async getHarvestAddress() {
    try{
      //1.获取用户的授权情况
    const result1 = await z_getSetting()
    const scopeAddress = result1.authSetting['scope.address']
    if(scopeAddress === false){
      //3.诱导用户打开设置授权jiemian
      const result3 = await z_openSetting()
      if(result3.authSetting['scope.address']){
        const address = await z_chooseAddress()
        wx.setStorageSync('address', address)
        this.setData({address})
      }
      return     
    }
    //2.如果为true或者undefind,调用获取地址
    const address = await z_chooseAddress()
    this.setData({address})
    wx.setStorageSync('address', address)
    }catch(error){
      console.log(error)
    }
    
    
  },

  //页面初始化从本地存储中获取收货地址
  getAddress() {
    const address = wx.getStorageSync('address') || {};
    this.setData({address})

  },
  

  
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getGoodsInfo()
    this.getTotalPriceCount()
    this.selectComponent('#cart_bar').isSelect()
  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})